﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FlexminAPI;
using System.Net.NetworkInformation;
using System.Net;

namespace NetStatistics
{
	public class NetSlave : ISlave
	{
		private NetSpeedMonitor speedMonitor;

		private IPGlobalProperties ipProperties;

		public NetSlave()
		{
			speedMonitor = new NetSpeedMonitor();
			ipProperties = IPGlobalProperties.GetIPGlobalProperties();
		}

		private string hostName;
		public string HostName
		{
			get { return hostName; }
		}

		private string nodeType;
		public string NodeType
		{
			get { return nodeType; }
		}

		private string dhcpScopeName;
		public string DhcpScopeName
		{
			get { return dhcpScopeName; }
		}

		private string domainName;
		public string DomainName
		{
			get { return domainName; }
		}

		public TcpConnectionInfo[] GetActiveTcpConnections()
		{
			List<TcpConnectionInfo> tcpInfos = new List<TcpConnectionInfo>();
			
			foreach (TcpConnectionInformation tcpInfo in ipProperties.GetActiveTcpConnections())
			{
				TcpConnectionInfo info = new TcpConnectionInfo();
				info.LocalAddress = tcpInfo.LocalEndPoint.Address.ToString();
				info.LocalPort = tcpInfo.LocalEndPoint.Port;
				info.RemoteAddress = tcpInfo.RemoteEndPoint.Address.ToString();
				info.RemotePort = tcpInfo.RemoteEndPoint.Port;
				info.State = tcpInfo.State.ToString();
				
				tcpInfos.Add(info);
			}

			return tcpInfos.ToArray();
		}

		public ActiveListener[] GetActiveListeners()
		{
			List<ActiveListener> activeListeners = new List<ActiveListener>();

			foreach (IPEndPoint ipEndPoint in ipProperties.GetActiveTcpListeners())
				activeListeners.Add(new ActiveListener(ipEndPoint, NetProtocol.TCP));

			foreach (IPEndPoint ipEndPoint in ipProperties.GetActiveUdpListeners())
				activeListeners.Add(new ActiveListener(ipEndPoint, NetProtocol.UDP));

			return activeListeners.ToArray();
		}		

		public NetworkAdapter[] GetAdapters()
		{
			return speedMonitor.Adapters;
		}

		public void StartSpeedMonitoring()
		{
			speedMonitor.StartSpeedMonitoring();
		}

		public void StopSpeedMonitoring()
		{
			speedMonitor.StopSpeedMonitoring();
		}

		public void Refresh()
		{
			ipProperties = IPGlobalProperties.GetIPGlobalProperties();
			hostName = ipProperties.HostName;
			domainName = ipProperties.DomainName;
			nodeType = ipProperties.NodeType.ToString();
			dhcpScopeName = ipProperties.DhcpScopeName;		
		}
	}
}
